<template>
    <view class="picker-date" v-if="show" @touch.stop.prevent="">
		<view class="mask" @click="show = false"></view>
		<view class="content">
			<view class="sure">
				<text @click="sure">确定</text>
			</view>
			<picker-view 
				class="picker-view" 
				indicator-style="height: 100rpx;" 
				:value="value" 
				@change="bindChange" 
				@pickstart="pickstart"
				@pickend="pickend"
			>
				<picker-view-column>
					<view class="item" v-for="(item, index) in years" :key="index">
						{{ item }}
					</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item, index) in months" :key="index">
						{{ item }}
					</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item, index) in days" :key="index">
						{{ item }}
					</view>
				</picker-view-column>
			</picker-view>
		</view>
	</view>
</template>
<script>
export default {
    components: {},
    data() {
        return {
			show: false,				// 是否显示
			value: [85, 0, 0],			// 默认索引
			years: [],					// 年份数组
			months: [],					// 月份数组
			days: [],					// 天数数组
			pickerIndex: [],			// 选择的索引
			canClick: true,				// 是否可以点击确定,滚动时不可点击
			// birthday: ''
		};
    },
    computed: {},
    methods: {
		// 循环出年（或月或日）的数组
		loop(obj) {
			let {start, end, name} = obj
			for(let i = start; i <= end; i++){
				if(i < 10) {
					i = '0' + i
				}
				this[name].push(i)
			}
		},
		// 选择器改变
		bindChange(e) {
			let val = e.detail.value
			setTimeout(() => {
				this.pickerIndex = val
			})
			let date = new Date(this.years[val[0]], this.months[val[1]], 0)
			let day = date.getDate()
			// 更改天数数组
			this.days = []
			this.loop({
				start: 1, 
				end: day, 
				name: 'days'})
		},
		// 开始滚动
		pickstart() {
			this.canClick = false
		},
		// 滚动结束
		pickend() {
			setTimeout(() => {
				this.canClick = true
			})
		},
		// 确认出生日期
		sure() {
			if(!this.canClick) return;
			this.show = false
			let index = []
			if(this.pickerIndex.length !== 0){
				index = this.pickerIndex
				this.value = this.pickerIndex
			}else {
				index = this.value
			}
			let year = this.years[index[0]]
			let month = this.months[index[1]]
			let day = this.days[index[2]]
			let birthday = year + '-' + month + '-' + day
			this.$emit('sure',birthday)
		},
	},
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {
		let data = new Date()
		this.loop({
			start: 1900, 
			end: data.getFullYear(), 
			name: 'years'})
		this.loop({
			start: 1, 
			end: 12, 
			name: 'months'})
		this.loop({
			start: 1, 
			end: 31, 
			name: 'days'})
	},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
};
</script>
<style scoped lang='scss'>
@import "./index.scss";
</style>
